package com.zing.task;

import com.zing.entity.Orders;
import com.zing.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    // 支付超时订单处理 15分钟未支付订单自动修改状态为 已取消
    //@Scheduled(cron="0 * * * * ? ") //每分钟执行一次
    public void processTimeoutOrder(){
        log.info("定时任务开始处理超时订单: {}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
       List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
       if(ordersList != null && ordersList.size() >0) {
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("超时未支付, 自动取消");
               orders.setCancelTime(LocalDateTime.now());
               orderMapper.update(orders);
           }
       }
    }

    // 派送中订单处理 一直处于派送中订单自动修改状态为 已完成
    @Scheduled(cron="0 0 2 * * ? ") // 每天凌晨2点执行
    public void processDeliveryOrder(){
        log.info("开始进行未完成订单状态处理: {}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-120);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }



    }
}
